import Vue from 'vue'
import VueRouter from 'vue-router'
import { store } from '../store/store'
import Login from '../views/Login'
import bookList from '../views/BookList'
import MyBookList from '../views/MyBookList'
import Book from '../views/Book'
import Layout from '../components/layout/Layout'
import Main from '../views/Main.vue'
import Mine from '../views/Mine.vue'
import RegInfo from '../views/RegInfo.vue'
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

export const routes = [
  {
    path: '/',
    name: 'Main',
    // component: Login
    component: Main
  },
  {
    path: '/401',
    name: '401',
    component: resolve => require(['../components/401.vue'], resolve),
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/bookList',
    name: 'bookList',
    component: bookList
  },
  {
    path: '/myList',
    name: 'myList',
    component: MyBookList
  },
  {
    path: '/book',
    name: 'book',
    component: Book
  },
  {
    path: '/myInfo',
    name: 'myInfo',
    component: Mine
  },
  {
    path: '/regInfo',
    name: 'regInfo',
    component: RegInfo
  },
]
const router = new VueRouter({
  routes: routes,
  //mode: 'history'
})

// 全局守卫 需要跳转的路由to
router.beforeEach((to, form, next) => {
  // eslint-disable-next-line eqeqeq
  if (to.path == '/login' || to.path == '/') {
    next()
  } else {
    console.log('to.path' + to.path)
    const token = store.state.token
    const menus = store.state.menus
    // 校验全选
    let hasRole = false
    //
    if (to.meta.requestLogin) {
      // 校验是否需要检验登录
      if (token == null || token == '') {
        Vue.$vux.alert.show({
          title: '提示',
          content: '登录过期,请重新登录',
          onShow() {
          },
          onHide() {
            next('/')
          }
        })
      } else {
        // 是否需要校验权限
        if (to.meta.permissions) {
          menus.forEach(item => {
            if (to.path == '/' + item.link) {
              hasRole = true
              return
            }
          })
          if (hasRole) {
            next()
          } else {
            next('/401')
          }
        } else {
          next()
        }
      }
    } else {
      next()
    }
  }
})
router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});
// });
// 后置钩子
// router.afterEach((to, form) => {
//   alert("afterEach");
// });
export default router
